import openai
from typing import Generator

def handler_factory(model: str, api_key: str, base_url: str = "https://api.openai.com/v1"):
    openai.api_key = api_key
    openai.api_base = base_url

    def handler(query: str) -> Generator[str, None, None]:
        try:
            response = openai.ChatCompletion.create(
                model=model,
                messages=[{"role": "user", "content": query}],
                stream=True
            )

            for chunk in response:
                if "choices" in chunk:
                    delta = chunk["choices"][0]["delta"]
                    if "content" in delta:
                        yield delta["content"]
        except Exception as e:
            yield f"[OpenAI Error] {str(e)}"

    return handler
